package workqueues;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author wangjinqiang
 * @date 2019-08-06
 */
public class Worker {
    private static final String QUEUE_NAME = "task_queue";

    /**
     * 1. 设置消息持久化
     * 生产者:
     * 队列声明 durable = true: channel.queueDeclare(QUEUE_NAME, true, false, false, null);
     * props(MessageProperties.PERSISTENT_TEXT_PLAIN deliveryMode:2) : channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes(StandardCharsets.UTF_8));
     * 消费者:
     * 队列声明 durable = true: channel.queueDeclare(QUEUE_NAME, true, false, false, null);
     * <p>
     * 2. 开启手动ACK
     * channel.basicQos(1);
     * channel.basicConsume(autoAck: false):  channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> {
     * DeliverCallback.handle(): channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
     */
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        channel.basicQos(1);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String recvMessage = new String(message.getBody());

            System.out.println(" [x] Receive '" + recvMessage + "'");
            try {
                doWork(recvMessage);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println(" [x] Done");
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }
        };
        channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> {
        });
    }

    private static void doWork(String task) throws InterruptedException {

        for (char c : task.toCharArray()) {
            if (c == '.') {
                Thread.sleep(1000);
            }
        }
    }
}
